# -*- coding: UTF-8 -*-
from flask import Flask, request, send_file, render_template, flash, redirect, url_for, make_response, jsonify, abort
import os
import time
import shutil
import gzip
import requests
from flask_restful import Api, Resource, reqparse
from towergame import service_list
from lark import lark_message_card, lark_upload_image
from nebula import vscode

UPLOAD_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'download')
app = Flask(__name__)
app.config['SECRET_KEY'] = 'nreal'
api = Api(app)

# 跨域
@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response

@app.route('/gateway')
def gateway():
    return jsonify(service_list)

@app.route('/api/v1/lark/notication', methods=["POST"])
def lark_notication():
    title = request.form.get("title")
    text = request.form.get("text")
    user_url = request.form.get("user_url")
    url = request.form.get("url")
    avator = request.form.get("avator")
    media_type = request.form.get("media_type")
    media_url = request.form.get("media_url")
    post_url = "https://open.feishu.cn/open-apis/bot/v2/hook/c3b19c05-a1cf-40c6-8f31-a8420b7dc6d3"
    media_list = []
    if media_type == "photo":
        media_key = lark_upload_image(media_url)
        media_list.append(media_key)
    res = lark_message_card(post_url, title, text, media_list, url, user_url)
    return jsonify(res)


@app.route('/upload/', methods=['POST', 'DELETE'])
def upload_file():
    # white_ip = ['103.206.188.29','36.112.85.98']
    # ip = request.remote_addr
    # if ip not in white_ip:
    #     return "no access",401
    if request.method == 'POST':
        file = request.files.get('filename')
        # 获取原文件名
        # src_filename = secure_filename(file)
        # 获取rename文件名
        filename = request.form.get('file')
        # filename = request.form.get('file', src_filename)
        if not filename:
            flash(' error! filename is null')
            return redirect(url_for('upload_file'))
        date = time.strftime('%Y-%m-%d', time.localtime())
        
        if not os.path.exists(os.path.join(UPLOAD_DIR, date)):
            os.makedirs(os.path.join(UPLOAD_DIR, date))
        file_path = os.path.join(UPLOAD_DIR, date, filename)

        file_sets = os.listdir(os.path.join(UPLOAD_DIR, date))
        if filename in file_sets:
            os.remove(os.path.join(UPLOAD_DIR, date, filename))
        file.save(file_path)
        if file_path.endswith('.gz'):
            fin = gzip.open(file_path, 'rb')
            fout_name = file_path[:-3]
            if not fout_name.endswith('.log'):
                fout_name = fout_name+'.log'
            fout = open(fout_name, 'wb')
            while True:
                buf = fin.read()
                if len(buf) < 1:
                    break
                fout.write(buf)
            fin.close()
            fout.close()
            os.remove(file_path)
            
        flash('upload success')
        return redirect(url_for('upload_file'))
    elif request.method == 'DELETE':
        # 清空文件夹
        password = request.form.get('password')
        dirname = request.form.get('dirname')
        if password and password == 'Nreal123456' and dirname:
            if dirname in os.listdir(UPLOAD_DIR):
                shutil.rmtree(os.path.join(UPLOAD_DIR, dirname))
            elif dirname == 'all':
                shutil.rmtree(UPLOAD_DIR)
                os.makedirs(UPLOAD_DIR)
                return 'Delete All Files'
            else:
                return '%s not exists' % dirname
            return 'Delete all files in %s' % dirname
        return 'Permission denied'

    return render_template('upload.html')


@app.route('/download/<filename>', methods=['POST', 'GET'])
def download_file(filename):
    filename = filename
    file_path = os.path.join(UPLOAD_DIR, filename)
    if os.path.isfile(file_path):
        return send_file(file_path, as_attachment=True)
    else:
        return 'The download file does not exist'

@app.route('/')
def list_file():
    file_list = os.listdir(UPLOAD_DIR)
    return render_template('log.html', logfiles=file_list)

@app.route('/api/nebula')
def list_vscode():
    data = vscode
    return jsonify(data)

class ContactInfo(Resource):
    def post(self):
        if not request.json:
            abort(404)
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, help='please input username', required=True, location='json')
        parser.add_argument('email', type=str, help='please input email', required=True, location='json')
        parser.add_argument('tel', type=str, location='json')
        parser.add_argument('company', type=str, help='please input company', required=True, location='json')
        parser.add_argument('region', type=str, help='please input region', location='json')
        parser.add_argument('country', type=str, help='please input country', location='json')
        parser.add_argument('purpose', type=str, help='please input purpose', required=True, location='json')
        parser.add_argument('message', type=str, help='please input message', location='json')
        parser.add_argument('position', type=str, help='please input position', location='json')
        args = parser.parse_args()
        args = dict(args)

        name = args.get("name")
        email = args.get("email")
        tel = args.get("tel", "")
        company = args.get("company")
        purpose_map = {
            "1": ["option1", "Business Collaboration"],
            "2": ["h0583Agq1", "Personal Purchase"],
            "3": ["yLw28jrW3", "Developer"],
            "4": ["7k3Dtu0t6", "Customer Support"]
        }
        purpose = ""
        if args.get("purpose"):
            purpose = purpose_map[args.get("purpose")][0]
        message = args.get("message")
        region_map = {
            "1": ["SGrqo578a", "f722b96fe8304d4fa58b7c4f888a59c4", "Asia Pacific"],
            "2": ["DzI741Gdh", "e1fb7dc28e5943efb3628a27cf1fec3b", "Europe"],
            "3": ["RDTEj806n", "e1fb7dc28e5943efb3628a27cf1fec3b", "North America"],
            "4": ["", "e1fb7dc28e5943efb3628a27cf1fec3b", "Others"]
        }
        region = ""
        leads_pool = ""
        if args.get("region"):
            region = region_map[args.get("region")][0]
            leads_pool = region_map[args.get("region")][1]

        country = args.get("country")
        position = args.get("position")
        result = create_record(name=name, email=email, tel=tel, company=company, region=region, leads_pool=leads_pool, country=country, purpose=purpose, message=message, position=position)
        code = result.get("errorCode")
        # if code == "0":
        #     return jsonify({"code": 0, "msg": "success"})
        # else:
        #     return jsonify({"code": 1, "msg": result["errorMessage"]})
        return jsonify({"code": code, "msg": result.get("errorMessage", "ok")})


def get_access_token():
    url = "https://open.fxiaoke.com/cgi/corpAccessToken/get/V2"
    appid = "FSAID_1318e02"
    appsecret = "9b021b468b3048feb9c2342ee2386d11"
    permanentcode = "F785A27776526B83B30229E81D28E931"
    req_data = {
        "appId": appid,
        "appSecret": appsecret,
        "permanentCode": permanentcode
    }
    res = requests.post(url, json=req_data)
    return res.json().get("corpAccessToken", None)

def create_record(name, email, tel, company, region, leads_pool, country, purpose, message, position):
    url = "https://open.fxiaoke.com/cgi/crm/v2/data/create"
    req_data = {
        "corpAccessToken": get_access_token(),
        "corpId": "FSCID_2BB0AF683B017C864FF2FE4FFB38B301",
        "currentOpenUserId": "FSUID_71E457D67671B4FA5FA7A63C0F7E9C68",
        "data": {
            "object_data": {
                "dataObjectApiName": "LeadsObj",
                "name": name,
                "email": email,
                "mobile": tel,
                "company": company,
                "field_8Lh2M__c": region,
                "leads_pool_id": leads_pool,
                "field_wAGyB__c": country,
                "field_YHxM1__c": purpose,
                "remark": message,
                "department": position,
                "source": "6"
            }
        }
    }
    res = requests.post(url, json=req_data)
    return res.json()

api.add_resource(ContactInfo, '/api/v1/crm/contact_us/', endpoint='contactinfo')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8089)
